package com.example.trafficsystem.controller;

import com.example.trafficsystem.entity.*;
import com.example.trafficsystem.repository.*;
import com.example.trafficsystem.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/student")
@CrossOrigin // 允许跨域
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private OrganizationRe organizationRe;
    @Autowired
    private StudentRe studentRe;

    @Autowired
    private TrainingPlanRe trainingPlanRepository;
    @Autowired
    private StudentRe studentRepository;
    @Autowired
    private ExamRecordRe examRecordRepository;
    @Autowired
    private TaskRe taskRe;

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody Student student) {
        String result = studentService.register(student);
        if ("注册成功".equals(result)) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Student account) {
        boolean isLogin = studentService.login(account.getPhone(), account.getPassword());

        if (isLogin) {
            // 如果登录成功，返回学生基本信息（可以添加更多字段）
            Student student = studentService.findByPhone(account.getPhone());
            Map<String, Object> response = new HashMap<>();
            response.put("id", student.getId());
            response.put("name", student.getName());
            response.put("phone", student.getPhone());
            response.put("organizationId", student.getOrganization().getId());
            // 添加更多返回字段，比如邮箱、地址等
            return ResponseEntity.ok(response);  // 登录成功时返回学生信息
        } else {
            // 登录失败，返回 400 错误及错误信息
            return ResponseEntity.badRequest().body(Map.of("message", "用户名或密码错误"));
        }
    }
    // 查看个人信息
    @GetMapping("/info")
    public ResponseEntity<Student> getStudentInfo(@RequestParam("id") Long studentId) {
        // 查找学生信息
        Student student = studentRe.findById(studentId).orElse(null);

        // 如果学生不存在，返回 400 错误
        if (student == null) {
            return ResponseEntity.badRequest().body(null);
        }

        // 返回 200 OK 和学生信息
        return ResponseEntity.ok(student);
    }

    // 编辑个人信息
    @PutMapping("/edit")
    public ResponseEntity<String> editStudentInfo(@RequestBody Student student) {
        // 查找学生是否存在
        Student existingStudent = studentRe.findById(student.getId()).orElse(null);
        if (existingStudent == null) {
            return ResponseEntity.badRequest().body("学生不存在");
        }
        // 更新其他可编辑的信息（不包括 id）
        existingStudent.setName(student.getName());
        existingStudent.setPhone(student.getPhone());
        existingStudent.setEmail(student.getEmail());
        existingStudent.setAddress(student.getAddress());
        // 密码字段可以根据需求是否允许更新
        if (student.getPassword() != null && !student.getPassword().isEmpty()) {
            existingStudent.setPassword(student.getPassword());
        }
        // 只有在传递了机构信息时才更新
        if (student.getOrganization() != null && student.getOrganization().getId() != null) {
            Organization organization = organizationRe.findById(student.getOrganization().getId()).orElse(null);
            if (organization != null) {
                existingStudent.setOrganization(organization);
            } else {
                return ResponseEntity.badRequest().body("指定的机构不存在");
            }
        }
        // 保存更新后的学生信息
        studentRe.save(existingStudent);
        return ResponseEntity.ok("个人信息更新成功");
    }
    //加入培训计划
    @PutMapping("/{studentId}/join/{trainingPlanId}")
    public ResponseEntity<Student>joinTrainingPlan(@PathVariable Long studentId, @PathVariable Long trainingPlanId){
        Student updatedStudent = studentService.joinTrainingPlan(studentId, trainingPlanId);
        return ResponseEntity.ok(updatedStudent);
    }
    @PutMapping("/{studentId}/withdraw")
    public ResponseEntity<Student> withdrawTrainingPlan(@PathVariable Long studentId) {
        // 查找学员
        Student student = studentRe.findById(studentId)
                .orElseThrow(() -> new RuntimeException("学员不存在"));

        // 检查学员是否已有培训计划
        TrainingPlan trainingPlan = student.getTrainingPlan();
        if (trainingPlan == null) {
            return ResponseEntity.badRequest().body(null);  // 如果学员没有选择培训计划，返回 400 错误
        }

        // 退选操作：将学员的培训计划设为 null
        student.setTrainingPlan(null);
        // 更新学员信息
        studentRe.save(student);

        // 返回更新后的学员信息
        return ResponseEntity.ok(student);
    }

    //根据培训计划ID查询课程
    @GetMapping("/{studentId}/trainingPlan")
    public ResponseEntity<TrainingPlan> getTrainingPlan(@PathVariable Long studentId) {
        Student student = studentRe.findById(studentId)
                .orElseThrow(() -> new RuntimeException("学员不存在"));

        TrainingPlan trainingPlan = student.getTrainingPlan();
        if (trainingPlan == null) {
            return ResponseEntity.badRequest().body(null);
        }

        return ResponseEntity.ok(trainingPlan);
    }



    // 获取学员的考试记录
    @GetMapping("/exam-records/{studentId}")
    public ResponseEntity<List<ExamRecord>> getExamRecords(@PathVariable Long studentId) {
        Student student = studentRepository.findById(studentId)
                .orElseThrow(() -> new IllegalArgumentException("Student not found"));

        List<ExamRecord> examRecords = examRecordRepository.findByStudent(student);
        return ResponseEntity.ok(examRecords);
    }

    // 下载考试报表（比如成绩单）
    @GetMapping("/exam-report/{studentId}")
    public ResponseEntity<byte[]> downloadExamReport(@PathVariable Long studentId) {
        // 生成报表
        byte[] report = generateExamReport(studentId);
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=exam_report.pdf")
                .body(report);
    }

    private byte[] generateExamReport(Long studentId) {
        // 这里可以根据学员的考试记录生成报表，生成 PDF 或 Excel 等格式
        // 你可以使用 Apache POI 来生成 Excel，或使用 iText 来生成 PDF
        return new byte[0];  // 示例返回空字节数组
    }
}
